package com.ali.service.impl;

import com.ali.common.BeanCopyUtil;
import com.ali.dao.UserMapper;
import com.ali.dto.UserInfo;
import com.ali.entity.User;
import com.ali.service.UserService;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplateImpl redisTemplateImpl;

    @Override
    public UserInfo getById(Map<String, Object> param) {
        Long id = Long.parseLong((String) param.get("id"));

        UserInfo userInfo = new UserInfo();

        User user;

        //先去Redis中查找，不存在则去数据库中查找
        String userJson = getRedisUserJson(id);
        log.info("userJson：" + userJson);

        if (StringUtils.isNotEmpty(userJson)) {
            user = JSON.parseObject(userJson, User.class);
        } else {
            user = userMapper.selectById(id);
            userJson = JSON.toJSONString(user);
            setRedisUserJson(id, userJson);
        }

        BeanCopyUtil.copyProperties(user, userInfo);
        return userInfo;
    }

    @Override
    public void update(Map<String, Object> param) {
        Long id = Long.parseLong((String) param.get("id"));

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("name", param.get("name"));
        updateWrapper.eq("id", id);

        userMapper.update(updateWrapper);

        deleteRedisUserJson(id);
    }

    /**
     * Redis设置
     */
    private void setRedisUserJson(Long id, String userJson) {
        redisTemplateImpl.set("user:" + id, userJson);
    }

    /**
     * Redis获取
     */
    private String getRedisUserJson(Long id) {
        return redisTemplateImpl.get("user:" + id);
    }

    /**
     * Redis删除
     */
    public void deleteRedisUserJson(Long id) {
        redisTemplateImpl.del("user:" + id);
    }
}